package com.jdy.haoduoai.wxapi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.OrderDetailsActivity;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.Tools;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.ycsj.goldmedalnewconcept.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

  private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

  private IWXAPI api;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pay_result);

    api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID);

    api.handleIntent(getIntent(), this);
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    api.handleIntent(intent, this);
  }

  @Override
  public void onReq(BaseReq req) {
  }

  private boolean queryPayState(String ordernumber, String sign) {
    String httpUrl = Uri.parse(OrderDetailsActivity.QUERY_STATE_URL)
        .buildUpon().appendQueryParameter("companyid", String.valueOf(1))
        .appendQueryParameter("corderid", ordernumber)
        .appendQueryParameter("sign", sign).build().toString();

    try {
      JSONObject jsonObj = HttpUtils.initiateHttpConnection(httpUrl,
          HttpUtils.TAG_POST_REQUEST, false);
      if (jsonObj.has("status")) {
        int status = jsonObj.getInt("status");
        // 支付成功!
        if (status == 1 || status == 2) {
          return true;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return false;
  }

  /**
   * 0 成功 展示成功页面 -1 错误 可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
   * -2 用户取消 无需处理。发生场景：用户不支付了，点击取消，返回APP。
   */
  @SuppressLint("LongLogTag")
  @Override
  public void onResp(final BaseResp resp) {
    Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

    if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {

      if (resp.errCode == 0) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.app_tip);
        builder.setMessage(getString(R.string.pay_result_callback_msg,
            resp.errStr + ";code=" + String.valueOf(resp.errCode)));
        builder.show();
      } else {
        new Thread() {
          @Override
          public void run() {
            if (Tools.isNotEmpty(LeXiaoXiaoBanApp.ordernumber)
                && queryPayState(LeXiaoXiaoBanApp.ordernumber, "yyyyyyyyyyy")) {
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  AlertDialog.Builder builder = new AlertDialog.Builder(
                      WXPayEntryActivity.this);
                  builder.setTitle(R.string.app_tip);
                  builder.setMessage("支付成功");
                  builder.show();
                }
              });
            } else {
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  AlertDialog.Builder builder = new AlertDialog.Builder(
                      WXPayEntryActivity.this);
                  builder.setTitle(R.string.app_tip);
                  builder.setMessage(getString(
                      R.string.pay_result_callback_msg, resp.errStr + ";code="
                          + String.valueOf(resp.errCode)));
                  builder.show();
                }
              });
            }
          }
        }.start();
      }

      // AlertDialog.Builder builder = new AlertDialog.Builder(this);
      // builder.setTitle(R.string.app_tip);
      // builder.setMessage(getString(R.string.pay_result_callback_msg,
      // resp.errStr + ";code=" + String.valueOf(resp.errCode)));
      // builder.show();
    }
  }
}